package com.alipay.demo.util;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;


/**
 * JackJson工具类
 *
 * @author : zhuzhiping
 * @date : 2020-12-24 19:21
 */
@Slf4j
public class JackJsonUtils {

    private static final ObjectMapper objectMapper;

    static {
        objectMapper = new ObjectMapper();
    }

    /**
     * 字符串转Map
     *
     * @param jsonStr
     * @return
     */
    public static Map<String, ?> getMap(String jsonStr) {
        if (jsonStr == null || "".equals(jsonStr = jsonStr.trim())) {
            return new HashMap<>(2);
        }
        JavaType type = objectMapper.getTypeFactory().constructParametricType(HashMap.class, String.class, Object.class);
        try {
            Map<String, ?> result = objectMapper.readValue(jsonStr, type);
            return result;
        } catch (Exception e) {
            log.error("字符串转Map异常", e);
        }
        return new HashMap<>(2);
    }


    /**
     * 对象转Map
     *
     * @param obj
     * @return
     */
    public static Map<String, ?> getMap(Object obj) {
        String jsonStr = getJSONStr(obj);
        if (jsonStr == null || "".equals(jsonStr = jsonStr.trim())) {
            return new HashMap<>(2);
        }
        return getMap(jsonStr);
    }

    /**
     * 对象转字符串
     *
     * @param obj
     * @return
     */
    public static String getJSONStr(Object obj) {
        if (obj == null) {
            return "";
        }
        if (obj instanceof String) {
            return (String) obj;
        }
        try {
            String result = objectMapper.writeValueAsString(obj);
            return result;
        } catch (Exception e) {
            log.error("对象转字符串异常", e);
        }
        return "";
    }


    /**
     * json字符串转JsonNode对象的方法
     */
    public static JsonNode str2JsonNode(String str) throws NullPointerException {
        try {
            return objectMapper.readTree(str);
        } catch (Exception e) {
            log.error("对象转字符串异常", e);
            return null;
        }
    }

    /**
     * 字符串转对象
     *
     * @param str
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T str2Obj(String str, Class<T> clazz) {
        try {
            objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            T obj = objectMapper.readValue(str, clazz);
            return obj;
        } catch (Exception e) {
            log.error("字符串转对象异常", e);
            return null;
        }
    }
}
